using System;
using System.Collections.Generic;

namespace Tycho.Parser.Peg {
    public class CompositeTermBuilder : ICompositeTermBuilder {
        private HashSet<string> MultipleSet;

        public CompositeTermBuilder (IEnumerable<string> multiples) {
            Multiples = multiples;
        }

        public IEnumerable<string> Multiples {
            get {
                if (MultipleSet != null) {
                    return MultipleSet;
                } else {
                    return new string[0];
                }
            }
            set {
                if (value != null) {
                    MultipleSet = new HashSet<string> (value);
                } else {
                    MultipleSet = null;
                }
            }
        }

        public void Build (CompositeTerm term, IEnumerable<Capture> captures) {
            foreach (var capture in captures) {
                term.Add (capture.Name, capture.Term, IsMultiple (capture));
            }

            if (MultipleSet != null) {
                foreach (string captureName in MultipleSet) {
                    if (!term.SubTerms.ContainsKey (captureName)) {
                        term.Add (captureName, new ListTerm (term.SourceInformation), false);
                    }
                }
            }
        }

        private bool IsMultiple (Capture capture) {
            return MultipleSet != null && MultipleSet.Contains (capture.Name);
        }
    }
}